extends CharacterBody2D
class_name BulletAutoTrace

@onready var lifeTimer:Timer = $LifeTimer
@onready var spr = $Sprite2D
@onready var hpBar = $HP/TextureProgressBar

@export var angleForce = 2.5
@export var maxLifeTime = 10
@export var speed = 100
@export var maxHp = 20

var hp
var traceTarget:Node2D


func setVelocity(value):
	velocity = value
	

func setTarget(obj):
	traceTarget = obj
	
	
func _ready():
	hp = maxHp
	updateHpUI()
	
	var initDir = Global.angle2Vector(randf() * 360) 
	setVelocity(initDir * speed)
	
	lifeTimer.wait_time = maxLifeTime
	lifeTimer.timeout.connect(die)
	lifeTimer.start()
	

func die():
	queue_free()


func _physics_process(delta):
	if traceTarget != null:
		traceProcess(delta)
	
	move_and_slide()
	
	if position.x < -10 or position.x > 190 or position.y < -10 or position.y > 330:
		die() 
	
	
func traceProcess(delta):
	var currentDir = velocity.normalized()
	var targetDir = (traceTarget.global_position - global_position).normalized()
	targetDir = currentDir.lerp(targetDir, angleForce * delta)
	velocity = targetDir * speed
	spr.rotation = deg_to_rad(Global.vector2Angle(targetDir))
	
	
func onHit(damage):
	hp -= damage
	if hp <= 0:
		die()
	
	updateHpUI()
	

func _on_bullet_auto_trace_hit_area_area_entered(area:Area2D):
	if area.name == "PlayerHitArea":
		area.onHit()
		die()
		

func updateHpUI():
	hpBar.value = hp * 1.0 / maxHp
